//
//  GiftCollectionViewController.m
//  Preject_B
//
//  Created by lanou on 15/12/16.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "GiftCollectionViewController.h"
#import "GiftCollectionViewCell.h"
#import "GiftModel.h"
#import "HotCollectionViewController.h"
@interface GiftCollectionViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, retain)NSMutableArray *keyArray;
@property (nonatomic, retain)NSMutableDictionary *modelDic;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSIndexPath *indexPath;
@property (nonatomic, retain)UITableViewCell *cell;

@end

@implementation GiftCollectionViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self setdata];
    [self setflowLayout];
    [self.collectionView registerClass:[GiftCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    [self setframe];
    [self setTableView];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
    
}







- (void)setframe
{
    CGRect rect = self.collectionView.frame;
    rect.origin.x = kWidth * 0.25;
    rect.origin.y = 66;
    rect.size.width = kWidth * 0.75;
    rect.size.height -= 90;
    self.collectionView.frame = rect;
}



- (void)setflowLayout
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    flowLayout.itemSize = CGSizeMake(kWidth / 4.0 - 20, 120);
    //    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.collectionViewLayout = flowLayout;
}




- (void)setdata
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *savedEncodedData = [defaults objectForKey:@"GiftModelDic"];
    NSData *savedEncodedData2 = [defaults objectForKey:@"GiftKeyArray"];
    
    if (savedEncodedData != nil) {
        _modelDic = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:savedEncodedData];
        _keyArray = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:savedEncodedData2];
        return;
    }else
    {
        
        [LORequestManger GET:kGiftAll success:^(id response) {
            _modelDic = [NSMutableDictionary dictionary];
            _keyArray = [NSMutableArray array];
            
            NSDictionary *rootDic = (NSDictionary *)response;
            
            NSArray *rootArr = rootDic[@"data"][@"categories"];
            for (NSDictionary *dic in rootArr) {
                [_keyArray addObject:dic[@"name"]];
                NSMutableArray *modelArray = [NSMutableArray array];
                for (NSDictionary *dic2 in dic[@"subcategories"]) {
                    GiftModel *model = [[GiftModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic2];
                    [modelArray addObject:model];
                    model.imageIcon = [self imageWithUrl:model.icon_url];
                }
                [_modelDic setObject:modelArray forKey:dic[@"name"]];
                if (_keyArray.count == 2) {
                    [self.collectionView reloadData];
                }
            }
            
            if (savedEncodedData == nil) {
                [_tableView reloadData];
                [self.collectionView reloadData];
            }
            
            
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_modelDic];
            [defaults setObject:data forKey:@"GiftModelDic"];
            NSData *data2 = [NSKeyedArchiver archivedDataWithRootObject:_keyArray];
            [defaults setObject:data2 forKey:@"GiftKeyArray"];
            
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];
        
    }
    
}

- (UIImage *)imageWithUrl:(NSString *)urlStr
{
    NSURL *url = [NSURL URLWithString:urlStr];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    return image;
}



#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _keyArray.count;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_modelDic[_keyArray[section]] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GiftCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.model = _modelDic[_keyArray[indexPath.section]][indexPath.row];
        // Configure the cell
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotCollectionViewController *topList = [[HotCollectionViewController alloc] initWithCollectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
    [topList setHidesBottomBarWhenPushed:YES];
    
    GiftModel *model = _modelDic[_keyArray[indexPath.section]][indexPath.row];
    
    topList.ID = model.ID;
    
    
    NSLog(@"%@************",[_modelDic[_keyArray[indexPath.section]][indexPath.row] ID]);
    [self.navigationController pushViewController:topList animated:YES];
    
}



#pragma mark 区头相关

//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView" forIndexPath:indexPath];
    [self setHeaderView:indexPath :headerView];
    
    _cell.selected = NO;
    _cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.section]];
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.section] atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
    _cell.selected = YES;
    
    return headerView;
}




//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{

    return CGSizeMake(0, 20);
    
}




- (void)setHeaderView:(NSIndexPath *)indexPath :(UICollectionReusableView *)headerView
{
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:(CGRectMake(0, 10, kWidth * 0.75, 1))];
    imageV.backgroundColor = [UIColor grayColor];
    [headerView addSubview:imageV];
    
    UILabel *label = [[UILabel alloc] initWithFrame:(CGRectMake(0, 0, 80, 20))];
    label.backgroundColor = [UIColor whiteColor];
    label.center = imageV.center;
    label.text = _keyArray[indexPath.section];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:14];
    [headerView addSubview:label];
    
}




#pragma mark tableView相关

- (void)setTableView
{
    _tableView = [[UITableView alloc] initWithFrame:(CGRectMake(0, 66, kWidth * 0.25, kHeight - 120)) style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    
    _tableView.showsVerticalScrollIndicator = NO; // 关闭竖直方向滚动条
    
    
//    [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]].selected = YES;
    
    
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _keyArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.text = _keyArray[indexPath.section];
    cell.textLabel.font = [UIFont systemFontOfSize:12];
    cell.textLabel.textColor = [UIColor darkGrayColor];
    cell.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
    UIImageView *imageV = [[UIImageView alloc] init];
    imageV.backgroundColor = [UIColor whiteColor];
    cell.selectedBackgroundView = imageV;
    cell.selectedTextColor = kThemeColor;
    
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:(UICollectionViewScrollPositionCenteredVertically) animated:YES];
    
}






//- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    [_tableView cellForRowAtIndexPath:indexPath].backgroundColor = kThemeColor;
//    [_tableView cellForRowAtIndexPath:indexPath].textLabel.textColor = [UIColor whiteColor];
//    
//}







@end
